// pages/trolly/trolley.js

import { createStoreBindings } from 'mobx-miniprogram-bindings';
import { store } from '../../store/store';
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    result: [],
    sumYuan: 0,
    ordersUnpay: [],
    getTrolleyUrl: "/portal/trolley/myTrolley/",
    deleteTrolleyUrl: "/portal/trolley//delete",
    payUrl: "/portal/trolley/pay",
    urlIcon: "/icons/2.jpg",
  },

  onChange(event) {
    this.setData({
      result: event.detail,
    });
    // console.log(this.data.result);
    var sum = 0;
    this.data.result.forEach(element => {
      for (let index = 0; index < this.data.ordersUnpay.length; index++) {
        const it = this.data.ordersUnpay[index];
        if (it.id == element) {
          sum += it.orderMoney * 1;
        }
      }
      // sum += this.data.ordersUnpay[element-1].orderMoney * 1;
    });
    this.setData({
      sumYuan: sum,
    });
    // console.log(this.data.sumYuan);
  },

  // 获取购物车信息
  getTrolley() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });

    let url = this.data.getTrolleyUrl + this.getUser().id;
    wx.request({
      url: url,
      method: "GET",
      success: (res) => {
        console.log(res.data.data);
        this.updataTrolleyCount(res.data.data.length);

        // 日期格式化
        for (let index = 0; index < res.data.data.length; index++) {
          res.data.data[index].infoDate = this.formatDate(res.data.data[index].infoDate);
        }

        this.setData({
          ordersUnpay: res.data.data
        })
        Toast.clear();
      },
      complete: () => {
        wx.stopPullDownRefresh();
      }
    })
  },

  delete(e) {
    console.log(e.currentTarget.dataset.id);
    Dialog.confirm({
      message: '确认删除',
    })
      .then(() => {
        // on confirm
        wx.request({
          url: this.data.deleteTrolleyUrl,
          method: "POST",
          data: {
            userId: this.getUser().id,
            orderId: e.currentTarget.dataset.id,
          },
          success: (res) => {
            Toast(res.data.msg);
            this.getTrolley();
            this.setData({
              result: [],
              sumYuan: 0,
            })
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  pay() {
    if (this.data.result.length == 0) {
      Toast("请选择订单");
      return;
    }

    Dialog.confirm({
      message: '确认支付' + this.data.sumYuan + '元',
    })
      .then(() => {
        // on confirm
        Toast.loading({
          message: '加载中...',
          forbidClick: true,
          loadingType: 'spinner',
        });

        console.log(this.data.result);
        wx.request({
          url: this.data.payUrl,
          method: "POST",
          data: {
            ids: this.data.result,
            userId: this.getUser().id,
          },
          success: (res) => {
            Toast(res.data.msg);
          },
          fail: (res) => {},
          complete: () => {
            setTimeout(() => {
              // 刷新数据
            this.getTrolley();
            }, 1000)
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  formatDate (time) {
    var date = new Date(time);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    var hour = function () { //获取小时
        return date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    }
    var minute = function () { //获取分钟
        return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    }

    var second = function () { //获取秒数
        return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    }
    return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ':' + second()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['trolleyCount'],
      actions: ['updataTrolleyCount', "getUser", 'getWebsite']
    });

    this.setData({
      getTrolleyUrl: this.getWebsite() + this.data.getTrolleyUrl,
      deleteTrolleyUrl: this.getWebsite() + this.data.deleteTrolleyUrl,
      payUrl: this.getWebsite() + this.data.payUrl,
      urlIcon: this.getWebsite() + this.data.urlIcon,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(this.getUser() == null) {
      this.setData({
        ordersUnpay: []
      })
    }

    if (this.getUser() != null) {
      this.getTrolley();
    }
    this.updataTrolleyCount(this.data.ordersUnpay.length);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 销毁挂载绑定
    this.storeBindings.destroyStoreBindings()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 刷新数据
    this.getTrolley();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})